package com.jcnet.bizaia;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import com.actionbarsherlock.app.SherlockActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcnet.bizaia.R.id;
import com.jcnet.bizaia.adapter.AdressCityAdapter;
import com.jcnet.bizaia.adapter.AdressCountryAdapter;
import com.jcnet.bizaia.bean.AdressHttpBean;
import com.jcnet.bizaia.bean.CityBean;
import com.jcnet.bizaia.bean.CountryBean;
import com.jcnet.bizaia.bean.SPSetting;
import com.jcnet.bizaia.bean.SPUserBean;
import com.jcnet.bizaia.bean.UserHttpBean;
import com.jcnet.bizaia.tools.DataStorageHelper;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.ProgressHUD;
import com.jcnet.bizaia.xstream.XmlCacheHelper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class FirstInAdressActivity extends Activity implements OnClickListener,OnItemClickListener{

	private TextView commActionTextView;

	private LinearLayout countryLinearLayout;
	private LinearLayout cityLinearLayout;

	private ListView  countryListView;
	private ListView  cityListView;


	private TextView cityNameTextView;

	private TextView countryNameTextView;

	private ImageView cityImageView;

	private ImageView countryImageView;

	ProgressHUD progressHUD;

	private AdressCountryAdapter adapter;

	private AdressCityAdapter cityAdapter;

	private List<CountryBean> countryNames;

	private List<CityBean> cityNames;

	private XmlCacheHelper xmlCacheHelper ;

	public static final String CACHE_DATA_ADRESS ="adress";  

	private Map<String, CountryBean> allAdressData;

	private boolean isCountryOpen = false; 

	private boolean isCityOpen = true;

	
	private CountryBean chooseCountryBean;
	
	private CityBean chooseCityBean;

	
	private DataStorageHelper setrttingDataStorageHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.choose_adress);

		xmlCacheHelper = new XmlCacheHelper(this);
		setrttingDataStorageHelper = new DataStorageHelper(this, SPSetting.SETTING_TABLE_NAME);
		
		commActionTextView=(TextView)findViewById(R.id.comm_action_text);
		commActionTextView.setText(getText(R.string.chooseAdress));

		countryLinearLayout=(LinearLayout)findViewById(R.id.countryLin);
		cityLinearLayout =(LinearLayout)findViewById(R.id.cityLin);

		countryLinearLayout.setOnClickListener(this);
		cityLinearLayout.setOnClickListener(this);

		countryListView =(ListView)findViewById(R.id.countryList);
		cityListView =(ListView)findViewById(R.id.cityList);

		cityNameTextView = (TextView)findViewById(R.id.cityName);
		countryNameTextView =(TextView)findViewById(R.id.countryName);

		cityImageView = (ImageView)findViewById(R.id.cityImg);
		countryImageView = (ImageView)findViewById(R.id.countryImg);


		//初始化区域
		countryNames = new ArrayList<CountryBean>();

		cityNames = new ArrayList<CityBean>();

		allAdressData= new HashMap<String, CountryBean>();

		adapter = new AdressCountryAdapter(this, countryNames);

		cityAdapter = new AdressCityAdapter(this, cityNames);
		
		chooseCityBean = new CityBean();
		
		chooseCountryBean = new CountryBean();


		countryListView.setOnItemClickListener(this);
		cityListView.setOnItemClickListener(this);

		countryListView.setAdapter(adapter);
		cityListView.setAdapter(cityAdapter);

		if(xmlCacheHelper.Xml2Object(CACHE_DATA_ADRESS)==null){
			getAdressFromSever();
			progressHUD = ProgressHUD.show(this, getString(R.string.dataloding), false, true, null);
		}else{
			allAdressData = (Map<String, CountryBean>) xmlCacheHelper.Xml2Object(CACHE_DATA_ADRESS);
			for (String name : allAdressData.keySet()) {
				countryNames.add(allAdressData.get(name));
			}

			adapter.count = countryNames.size();
			adapter.notifyDataSetChanged();
		}

		
		findViewById(R.id.adressOkbutton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(chooseCountryBean!=null){
				setrttingDataStorageHelper.putInt(SPSetting.CHOOSE_COUNTRY_ID, chooseCountryBean.getDisid());
				
				//少一个判断 当选择的地区为空的时候 不能写入数据
				
				setrttingDataStorageHelper.putInt(SPSetting.CHOOSE_PREFECTURE_ID, chooseCityBean.getDisid());
				
				setrttingDataStorageHelper.put(SPSetting.CHOOSE_COUNTRY_NAME, chooseCountryBean.getDisname());
				setrttingDataStorageHelper.put(SPSetting.CHOOSE_PREFECTURE_NAME, chooseCityBean.getDisname());
				
				}
				
				//第一次登录没有登录账户
				if(JCTools.isLogin(FirstInAdressActivity.this)){  //判断是否登录
					Intent intent = new Intent(FirstInAdressActivity.this, LoginActivity.class);
					intent.putExtra("firstIn", 100);
					startActivity(intent);
				}else{
					startActivity(new Intent(FirstInAdressActivity.this, MainActivity.class));
				}
				
				finish();
			}
		});

	}

	private void getAdressFromSever() {
		// TODO Auto-generated method stub

		if(Toolkit.isAvaliable(FirstInAdressActivity.this)){
			RequestParams params = new RequestParams();
			params.put("languageNum", App.localeCode);

			new AsyncHttpClient().post(App.HTTP_PATH+"dis_showDistrictsAll.action?", params, new AsyncHttpResponseHandler(){
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
					progressHUD.show();
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);

					System.out.println(new String(arg2));

					AdressHttpBean adressHttpBean = new Gson().fromJson(new String(arg2), new TypeToken<AdressHttpBean>(){}.getType());



					for (CountryBean countryBean : adressHttpBean.getObjlistJson()) {
						countryNames.add(countryBean);
						allAdressData.put(countryBean.getDisname(), countryBean);
					}


					xmlCacheHelper.Object2Xml(allAdressData, CACHE_DATA_ADRESS);
					adapter.count = countryNames.size();
					adapter.notifyDataSetChanged();

				}


				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(progressHUD.isShowing()){
						progressHUD.dismiss();
					}

				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					Toast.makeText(FirstInAdressActivity.this, getString(R.string.serverError	), 2).show();
					if(progressHUD.isShowing()){
						progressHUD.dismiss();
					}

				}
			});



		}else{
			Toast.makeText(FirstInAdressActivity.this, getString(R.string.noNetWork	), 2).show();
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.countryLin:
			if(isCountryOpen){
				countryImageView.setImageResource(R.drawable.down);
				countryListView.setVisibility(View.GONE);
			}else{
				countryListView.setVisibility(View.VISIBLE);
				countryImageView.setImageResource(R.drawable.up);
			}
			isCountryOpen = !isCountryOpen;
			break;
		case R.id.cityLin:
			if(isCityOpen){
				cityListView.setVisibility(View.GONE);
				cityImageView.setImageResource(R.drawable.down);
			}else{
				cityListView.setVisibility(View.VISIBLE);
				cityImageView.setImageResource(R.drawable.up);
				
				countryImageView.setImageResource(R.drawable.down);
				countryListView.setVisibility(View.GONE);
			}
			isCityOpen = !isCityOpen;
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.countryList:
			CountryBean countryBean = new CountryBean();
			countryBean  = allAdressData.get(countryNames.get(arg2).getDisname());

			cityNames.clear();
			if(countryBean!=null&&countryBean.getDistrictsJson()!=null){
				for (CityBean cityBean : countryBean.getDistrictsJson()) {

					cityNames.add(cityBean);

				}

			}

			cityAdapter.count = cityNames.size();
			cityAdapter.notifyDataSetChanged();
			countryNameTextView.setText(countryNames.get(arg2).getDisname());
			cityNameTextView.setText(getString(R.string.all));

			chooseCityBean = null;
			
			chooseCountryBean = countryBean;
			
			break;

		case R.id.cityList:
			cityNameTextView.setText(cityNames.get(arg2).getDisname());
			chooseCityBean = cityNames.get(arg2);
			
			break;
		default:
			break;
		}

	}



}
